package com.example.lemonservice.module.login.controller;

import com.example.lemoncommon.annotation.GetPermitNoAuth;
import com.example.lemoncommon.entity.Result;
import com.example.lemoncommon.enums.UserErrorEnum;
import com.example.lemoncommon.exception.ServiceException;
import com.example.lemonservice.entitiy.dto.LoginDTO;
import com.example.lemonservice.entitiy.vo.LoginUserVO;
import com.example.lemonservice.module.login.service.LoginServiceImpl;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.asn1.gm.GMNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.util.Base64;


@Slf4j
@Controller
public class LoginController {

    @Autowired
    LoginServiceImpl loginService;

    @PostMapping("/auth/login")
    @ResponseBody
    @GetPermitNoAuth
    @ApiOperation(value = "用户登录", notes = "根据输入的用户名和密码进行登录，返回用户token以及关联的角色权限信息")
    public Result<LoginUserVO> login(@RequestBody LoginDTO request) throws InvalidCipherTextException {
        request.setPassword(request.getPassword());
        LoginUserVO loginUserVO = loginService.login(request);
        if (loginUserVO == null) {
            throw new ServiceException(UserErrorEnum.ADMIN_NOT_EXISTED.getErrCode(), UserErrorEnum.ADMIN_NOT_EXISTED.getErrMsg());
        }
        return Result.SUCCESS(loginUserVO);
    }

    @RequestMapping(value = "/auth/logout", method = RequestMethod.DELETE)
    @ResponseBody
    @GetPermitNoAuth
    @ApiOperation(value = "用户退出登录", notes = "退出登录")
    public Result<Boolean> login(
            @ApiParam(name = "request", value = "当前用户token")
            @RequestHeader(name = "userToken") String token) {
        if (loginService.logOut(token)) {
            return Result.SUCCESS();
        } else {
            return Result.ERROR(null);
        }
    }


    private String sm2decode(String encodeStr) throws InvalidCipherTextException {
        //JS加密产生的密文
        byte[] cipherDataByte = Hex.decode(encodeStr);

        //刚才的私钥Hex，先还原私钥
        String privateKey = "00a0fcf9f83882db3f5279daafc6347dc126ca8586c996cf65dca6351d0fa465e7";
        BigInteger privateKeyD = new BigInteger(privateKey, 16);
        X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
        ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(), sm2ECParameters.getG(), sm2ECParameters.getN());
        ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(privateKeyD, domainParameters);
        //用私钥解密
        SM2Engine sm2Engine = new SM2Engine();
        sm2Engine.init(false, privateKeyParameters);

        //processBlock得到Base64格式，记得解码
        byte[] arrayOfBytes = Base64.getDecoder().decode(sm2Engine.processBlock(cipherDataByte, 0, cipherDataByte.length));

        //得到明文：SM2 Encryption Test
        return new String(arrayOfBytes);
    }
}
